Namespace = window.Namespace;
Namespace = Namespace || {};

if (window != top) {
	top.location.href = location.href;
}

function loadCss(href,callback){
    let script = document.createElement("link");
    script.rel = "stylesheet";
    if(script.readyState){
        script.onreadystatechange = function(){
            if(script.readyState==="loaded"||script.readyState==="complete"){
                script.onreadystatechange = null;
                callback();
            }
        }
    }else{
        script.onload = function(){
            callback();
        }
    }

    script.href = href;
    document.getElementsByTagName("head")[0].appendChild(script);
}

function loadScript(url,id,callback){
    let script = document.createElement("script");
    script.type = "text/javascript";
    script.id = id;
    if(script.readyState){
        script.onreadystatechange = function(){
            if(script.readyState==="loaded"||script.readyState==="complete"){
                script.onreadystatechange = null;
                callback();
            }
        }
    }else{
        script.onload = function(){
            callback();
        }
    }

    script.src = url;
    document.getElementsByTagName("body")[0].appendChild(script);
}


function fixZero(num,length){
	let str=""+num;
	let len=str.length;
	let s="";
	for(let i=length;i-->len;){
		s+="0";
	}
	return s+str;
}

function timeStamp2Month(timeStamp){
	if(timeStamp != null){
		let date=new Date(parseInt(timeStamp));
		return date.getMonth()+1;
	}
	return '';
}

function timeStamp2Day(timeStamp){
	if(timeStamp != null){
		let date=new Date(parseInt(timeStamp));
		return fixZero(date.getDate(),2);
	}
	return '';
}

function timeStamp2Time(timeStamp){
	if(timeStamp != null){
		let date=new Date(parseInt(timeStamp));
		return fixZero(date.getHours(),2)+":"+fixZero(date.getMinutes(),2);
	}
	return '';
}

function timeStamp2Date(timeStamp) {
	if(timeStamp != null){
		let date=new Date(parseInt(timeStamp));
		return date.getFullYear()+"-"+fixZero(date.getMonth()+1,2)+"-"+fixZero(date.getDate(),2)+" "+fixZero(date.getHours(),2)+":"+fixZero(date.getMinutes(),2)+":"+fixZero(date.getSeconds(),2);
	}
	return '';
}
function timeStamp2Date2(timeStamp) {
	if(timeStamp != null){
		let date=new Date(parseInt(timeStamp));
		return date.getFullYear()+"-"+fixZero(date.getMonth()+1,2)+"-"+fixZero(date.getDate(),2);
	}
	return '';
}

function date2timeStamp(datetime){
	let tmp_datetime = datetime.replace(/:/g,'-');
	tmp_datetime = tmp_datetime.replace(/ /g,'-');
	let arr = tmp_datetime.split("-");
	let now = new Date(Date.UTC(arr[0],arr[1]-1,arr[2],arr[3]-8,arr[4],arr[5]));
	return parseInt(now.getTime());
}


function AjaxRequest(opts) {
	this.type = opts.type || "POST";
	this.url = opts.url;
	this.param = opts.param;
	this.isShowLoader = (typeof(opts.isShowLoader) == 'undefined' ? true : opts.isShowLoader);
	this.dataType = opts.dataType || "json";
	this.callBack = opts.callBack;
	this.errorCallback = opts.errorCallback;
	this.complete = opts.complete;
	this.isCheckToken = opts.isCheckToken || false;
	this.contentType = opts.contentType || "application/json; charset=utf-8";
	this.async = (typeof(opts.async) == 'undefined' ? true : opts.async);
	this.timeout = opts.timeout || 1000000;
	this.headers = opts.headers || {};
	this.isCheckResult = (typeof(opts.isCheckResult) == 'undefined' ? true : opts.isCheckResult);
	this.showTips = (typeof(opts.showTips) == 'undefined' ? true : opts.showTips);
	this.init();
}

let layerIndex = 0;

AjaxRequest.prototype = {

	// 初始化
	init : function() {
		this.sendRequest();
	},
	// 渲染loader
	showLoader : function() {
		if (this.isShowLoader) {
			layerIndex = layer.load(3, {
				shade: [0.1,'#fff'] //0.1透明度的白色背景
			});
		}
	},
	// 隐藏loader
	hideLoader : function() {
		if (this.isShowLoader) {
			layer.close(layerIndex);
		}
	},
	
	// 发送请求
	sendRequest : function() {
		
		let self = this;
		/*if($('#layerjs').length === 0){
			loadScript('./js/layer.js','layerjs', function(){
				ajaxWithLoader(self);
			});
		}else{
			ajaxWithLoader(self);
		}*/
		ajaxWithLoader(self);

		function ajaxWithLoader(self){
			let obj = {};
			//obj.token = window.localStorage.getItem('token') || '';
			if (self.param) {
				self.param.token = obj.token;
				obj.body = self.param;
				obj.pageNo = self.param.pageNo ? self.param.pageNo : null;
				obj.pageSize = self.param.pageSize ? self.param.pageSize : null;
			}

			let param = self.contentType === "application/json; charset=utf-8" ? JSON.stringify(obj) : self.param;

			$.ajax({
				type : self.type,
				url : self.url,
				data : param,
				dataType : self.dataType,
				beforeSend : self.showLoader(),
				contentType: self.contentType,
				async: self.async,
				headers:self.headers,
				timeout: self.timeout,
				success : function(data, textStatus, request) {

					let msg = data?data.msg:'';
					if (data && data.code === 0){
						if (msg && self.showTips) {
							layer.msg(msg, {icon: 1, move: false, offset: 'auto', time: 1000});
						}
						if (self.callBack) {
							if (Object.prototype.toString.call(self.callBack) === "[object Function]") {
								self.callBack(data);
							} else {
								console.log("callBack is not a function");
								layer.alert("回调函数未定义！",{icon: 2});
							}
						}
					}else if (data && data.code === -5) {
						layer.alert(msg, {icon: 2, resize: false, offset: 'auto', move: false, anim: 1,title:'警告', closeBtn :0,shade: [0.8, '#393D49']}, function () {
							location.href = 'admin/'
						});
					}else{
						if(msg) {
							layer.alert(msg, {icon: 2, move: false, offset: 'auto'});
						}
						if (self.errorCallback) {
							if (Object.prototype.toString.call(self.errorCallback) === "[object Function]") {
								self.errorCallback();
							} else {
								console.log("errorCallback is not a function");
								layer.alert("错误回调函数未定义！",{icon: 2});
							}
						}
					}
				},
				error:function(xhr, textStatus, errorThrown){
					if (self.errorCallback) {
						if (Object.prototype.toString.call(self.errorCallback) === "[object Function]") {
							self.errorCallback(xhr, textStatus, errorThrown);
						} else {
							console.log("errorCallback is not a function");
							layer.alert("错误回调函数未定义！",{icon: 2});
						}
					}else{
						layer.alert("系统异常，请联系管理员！",{icon: 2});
					}
				},
				complete: function(){
					self.hideLoader();
					if (self.complete){
						self.complete();
					}
				}
			});
		}
	}
};
